<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" >
      <el-form-item label="食材名称" prop="name" v-show="showSearch">
        <el-input v-model="queryParams.name" placeholder="请输入食材名称" clearable style="width: 240px" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item v-show="showSearch">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
      <!--      <el-form-item >-->
      <!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>-->
      <!--      </el-form-item>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-form>
    <el-table v-loading="loading" :data="resourceList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="食材编号" prop="id" width="120" align="center"/>
      <el-table-column label="食材名称" prop="name" mi-width="120" align="center"/>
      <el-table-column label="食材类型" prop="type" mi-width="120" align="center"/>
<!--      <el-table-column label="食材图片" prop="imageUrl" align="center" :min-width="imageColWidth">-->
<!--        <template v-slot:default="scope">-->
<!--          <el-image v-for="(item,index) in scope.row.images"-->
<!--            style="width: 100px; height: 100px; margin-right: 15px"-->
<!--            :src="baseUrl + item">-->
<!--          </el-image>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="库存数量" width="150" align="center">-->
<!--        <template v-slot:default="scope">-->
<!--          <span>{{ scope.row.amount + scope.row.unit}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="均价" prop="avgPrice" width="90" align="center">
        <template v-slot="{row}">
          <span>{{row.avgPrice | currency}}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" prop="unit" width="90" align="center"/>
<!--      <el-table-column label="库存上限" prop="up" width="120" align="center"/>-->
<!--      <el-table-column label="库存下限" prop="down" width="120" align="center"/>-->
<!--      <el-table-column label="保质期" prop="guarantee" width="180" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.guarantee, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="创建人" prop="createBy" width="100" align="center"/>
      <el-table-column label="更新人" prop="updateBy" width="100" align="center"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改食材配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="食材名称" prop="name">
          <el-input :disabled="form.id" v-model="form.name" placeholder="请输入食材名称" />
        </el-form-item>
        <el-form-item label="食材类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择食材类型" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in dict.type.food_type" :key="index" :label="item.label"
                       :value="item.value" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="均价" prop="avgPrice" >
          <el-input v-model="form.avgPrice" placeholder="请输入均价" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请选择食材单位" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in foodUnit" :key="index" :label="item.dictLabel"
                       :value="item.dictValue" ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="库存上限" prop="up">-->
<!--          <el-input v-model="form.up" placeholder="请输入库存上限" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="库存下限" prop="down">-->
<!--          <el-input v-model="form.down" placeholder="请输入库存下限" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="保质期" prop="guarantee">-->
<!--          <el-date-picker v-model="form.guarantee" format="yyyy-MM-dd" value-format="yyyy-MM-dd"-->
<!--                          :style="{width: '100%'}" placeholder="选择请请购日期" clearable></el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="上传图片" prop="imageUrl" required>-->
<!--          <ImageUpload-->
<!--            v-model="form.imageUrl"-->
<!--            :limit="3"/>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listResource, getResource, delResource, addResource, updateResource } from "@/api/store/resource";
import {getDicts} from "@/api/system/dict/data";
const validatePass2 = (rule, value, callback) => {
  const pattern =/^[+]?([0-9]+(?:[.][0-9]*)?|\.[0-9]+)$/
  if ( value &&  !pattern.test(value)) {
    callback(new Error('请输入正数'))
  } else {
    callback()
  }
}
export default {
  name: "Resource",
  dicts: ['food_type'],
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      imageColWidth: 150,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 食材表格数据
      resourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      // 表单参数
      form: {
        imageUrl:'',
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "食材名称不能为空", trigger: "blur" }
        ],
        avgPrice: [{ validator: validatePass2, trigger: 'blur',required: false,}]
      },
      foodUnit:[]
    };
  },
  created() {
    this.getList();
    this.getDictData()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listResource(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          let maxWith = 1;
          for (var i = 0; i < response.rows.length; i++) {
            response.rows[i].images = [];
            if (response.rows[i].imageUrl != null && response.rows[i].imageUrl != undefined) {
              response.rows[i].images = response.rows[i].imageUrl.split(",");
            }
            if (response.rows[i].images.length > maxWith) {
              maxWith = response.rows[i].images.length;
            }
          }
          this.imageColWidth = maxWith * 150;
          this.resourceList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form={}
      // this.form.imageUrl='/profile/upload/2023/11/29/98f2f7ac42789d5e23e3cba321befd4.jpg'
      this.open = true;
      this.title = "添加食材";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getResource(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改食材";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateResource(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addResource(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const name = row.name;
      this.$modal.confirm('是否确认删除名称为"' + name + '"的食材？').then(function() {
        return delResource(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    getDictData(){
      getDicts('food_unit').then(res=>{
        this.foodUnit=res.data
      })
    },
  }
};
</script>
